import * as dd from 'dingtalk-jsapi';
import services from '../api/mine';
import config from '../config';
import axios from 'axios';
import {
  getURLParameter
} from '../utils';
import info from './mine/user';


const getCode = () => {
  return services.getJsConfig().then((res) => {
    const jsConfig = res.result;
    dd.config({
      ...jsConfig,
      jsApiList: [
        'biz.util.uploadImageFromCamera'
      ],
      onFail: (err) => console.log(err)
    });


    return new Promise((resolve, reject) => {
      dd.ready(function () {
        dd.runtime.permission.requestAuthCode({
          corpId: jsConfig.corpId,
          onSuccess: ({
            code
          }) => {
            config.dingtalk.code = code;
            resolve(code);
          },
          onFail: function (err) {
            console.log(err);
            reject(err);
          }
        });
      });
    });
  });
};

const setConfig = async () => {
  const appkey = getURLParameter('appkey');
  const corpId = getURLParameter('corpId');

  if (appkey) config.dingtalk.appKey = appkey;
  if (corpId) config.dingtalk.corpId = corpId;

  config.dingtalk.code = await getCode(config.dingtalk.corpId);
  return config.dingtalk;
}

export default async (to, next) => {
  const {
    dingtalk = false
  } = to.meta;

  if (!dingtalk) return false;

  const {
    appKey,
    corpId,
    code
  } = await setConfig();


  const
    res = await services.login({
      appkey: appKey,
      corpId,
      code
    });
  Object.assign(info, res.result.user);
  config.dingtalk.token = res.result.token;
  axios.defaults.headers.common['Authorization'] = res.result.token; //请求头文件

  next();

  return true;
};
